"""项目公共函数"""

import hmac
import random
import json
from logging import config, getLogger
from functools import wraps

from conf import settings


def get_salt():
    """返回由数字和大小写字母组成的长度是16的字符串"""
    s = 'abcdefghijklmnopqrstuvwxyz' \
        'ABCDEFGHIJKLMNOPQRSTUVWXYZ' \
        '0123456789'
    char_list = random.sample(s, 16)
    salt = ''.join(char_list)
    return salt


def encrypted_password(initial_password):
    """返回使用md5算法加密后的哈希值和加密使用的盐"""
    salt = get_salt()
    md5_obj = hmac.new(salt.encode('utf-8'), digestmod='md5')
    md5_obj.update(initial_password.encode('utf-8'))
    encrypted_pwd = md5_obj.hexdigest()
    return encrypted_pwd, salt


def get_logger(logger_name):
    """返回日志记录器"""
    config.dictConfig(settings.CONFIG_DICT)
    logger = getLogger(logger_name)
    return logger


def login_auth(func):
    """登录认证装饰器

    若用户已登录，则执行相应的功能；否则，执行登录功能。
    """
    from core import user_view

    @wraps(func)
    def wrapper(*args, **kwargs):
        if user_view.login_username:
            result = func(*args, **kwargs)
            return result
        else:
            print('请先登录!')
            user_view.login()
            result = func(*args, **kwargs)
            return result

    return wrapper


def get_phone():
    """返回手机字典"""
    with open(settings.PHONE_PATH, 'rt', encoding='utf-8') as f:
        phone = json.load(f)
        return phone


if __name__ == '__main__':
    result1 = get_phone()
    print(result1)
